import {
	ref
} from 'vue';

// 基础 URL
const BASE_URL = 'https://flyer.feishou.homes';

const getCode = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			success: resolve,
			fail: reject
		})
	})
}

const login = async () => {
	uni.showLoading({
		title: '加载中...',
		mask: true,
	});
	const res = await getCode();
	const answer = await uni.request({
		url: `${BASE_URL}/lgwx`,
		method: 'POST',
		data: {
			weixinCode: res.code
		}
	})
	uni.setStorageSync('token', answer.data && answer.data.data && answer.data.data.token);
}

// 请求拦截器
const requestInterceptor = async (config) => {
	const token = uni.getStorageSync('token');
	if(!token && !config.header.noToken) {
	   await login();
	}
	// 添加全局请求头
	config.header = config.header || {};
	config.header['baoflyflyertkn'] = uni.getStorageSync('token'); // 添加 token
	return config;
};

// 响应拦截器
const responseInterceptor = (response) => {
	// 统一处理响应数据
	if (response.statusCode === 200) {
		return response.data;
	} else {
		return Promise.reject(response.data);
	}
};

// 错误处理
const errorHandler = (error) => {
	// 统一处理错误
	uni.showToast({
		title: error.message || '请求失败，请稍后重试',
		icon: 'none',
	});
	return Promise.reject(error);
};

// 封装请求方法
const request = async (options) => {
	uni.showLoading({
		title: '加载中...',
		mask: true,
	});
	// 合并配置
	const config = {
		url: BASE_URL + options.url,
		method: options.method || 'GET',
		data: options.data || {},
		header: options.header || {},
	};

  // 请求拦截
  const finalConfig = await requestInterceptor(config);
	return new Promise((resolve, reject) => {
		uni.request({
			...finalConfig,
			success: (res) => {
				// 响应拦截
				const response = responseInterceptor(res);
				resolve(response);
			},
			fail: (err) => {
				// 错误处理
				errorHandler(err);
				reject(err);
			},
			complete: () => {
				uni.hideLoading();
			}
		});
	});
};

export default request;